﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Panos.Utils;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace Panos.Controllers
{
    public class ImageController : ApiController
    {
        [HttpGet]
        [Route("api/Images")]
        public HttpResponseMessage GetImages()
        {
            try
            {
                JArray images;
                var directory = HttpContext.Current.Request.MapPath("~/App_Data/images");
                var file = HttpContext.Current.Request.MapPath("~/App_Data/images/images.json");
                if (Directory.Exists(directory) == false)
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                if (File.Exists(file))
                {
                    using (var reader = new StreamReader(file))
                    {
                        images = JsonConvert.DeserializeObject<JArray>(reader.ReadToEnd());
                    }
                    if (images == null)
                        images = new JArray();
                }
                else
                {
                    File.Create(file);
                    images = new JArray();
                }
                foreach (var f in Directory.EnumerateFiles(directory, "*.jpg"))
                {
                    if (images.FirstOrDefault(token => token.Value<string>("name").Equals(Path.GetFileName(f))) != null)
                        continue;
                    using (var image = Image.FromFile(f))
                    {
                        images.Add(JObject.FromObject(new
                        {
                            Name = Path.GetFileName(f),
                            Longitude = image.GetPropertyTagGpsLongitude().GetDoubleValue(),
                            Latitude = image.GetPropertyTagGpsLatitude().GetDoubleValue(),
                            DateTime = image.GetPropertyTagDateTime()
                        }, new JsonSerializer() { ContractResolver = new CamelCasePropertyNamesContractResolver() }));
                    }
                }
                var removed = new List<JToken>();
                foreach (var f in images)
                {
                    var filename = Path.Combine(directory, f.Value<string>("name"));
                    if (File.Exists(filename) == false)
                        removed.Add(f);
                }
                foreach (var f in removed)
                    f.Remove();
                using (var writer = new StreamWriter(file))
                {
                    writer.Write(JsonConvert.SerializeObject(images));
                }
                return Request.CreateResponse(HttpStatusCode.OK, images);

            }
            catch (System.Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.StackTrace);
            }
        }

        [HttpGet]
        [Route("api/Image/{name}")]
        public HttpResponseMessage GetImage(string name)
        {
            var directory = HttpContext.Current.Request.MapPath("~/App_Data/images");
            if (Directory.Exists(directory) == false)
                return Request.CreateResponse(HttpStatusCode.NotFound);
            var path = Path.Combine(directory, name);
            if (File.Exists(path) == false)
                return Request.CreateResponse(HttpStatusCode.NotFound);

            var res = Request.CreateResponse(HttpStatusCode.OK);
            using (var image = Image.FromFile(path))
            {
                var ms = new MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                res.Content = new ByteArrayContent(ms.ToArray());
                res.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
                return res;
            }
        }
    }
}
